package com.ruoyi.common.utils;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.OrderTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author : Mr Li
 * @description : 单号生成
 * @since : 2023/6/25 15:34
 */
@Service
@Slf4j
public class OrderNoUtils {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public String generatedOrderNo(OrderTypeEnum orderTypeEnum) {
        String pre = orderTypeEnum.getPreFix();
        Date date = new Date();
        String dateFormat = DateUtil.format(date, orderTypeEnum.getRule());
        String redisKsy = Constants.SERIAL_NUMBER + ":" + orderTypeEnum.getType() + ":" + dateFormat;
        //先获取当前自增后的值
        Long incr = redisTemplate.opsForValue().increment(redisKsy);
        String formatPatten = "%04d";
        String format = String.format(formatPatten, incr);
        return pre + "-" + dateFormat + format;
    }

}
